package com.zw.yzk.kabu.data.network;

import android.content.Context;
import com.app.common.download.DownloadCallAdapterFactory;
import com.zw.yzk.kabu.data.constant.Constant;
import com.zw.yzk.kabu.data.utils.LogUtils;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import java.util.concurrent.TimeUnit;

/**
 * Created by wei on 2016/12/24.
 */
public class ServiceGenerator {

    private static OkHttpClient okHttpClient;
    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl(Constant.BASE_URL)
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(DownloadCallAdapterFactory.create());

    public static <T> T createService(Class<T> serviceClass) {
        Retrofit retrofit = builder.client(okHttpClient).build();
        return retrofit.create(serviceClass);
    }

    public static <T> T createPureService(Class<T> serviceClass) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Constant.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient).build();
        return retrofit.create(serviceClass);
    }

    public static void initService(Context context) {

        if (okHttpClient == null) {
            okHttpClient = new OkHttpClient()
                    .newBuilder()
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .cache(new Cache(context.getCacheDir(), 20 * 1024 * 1024))
//                    .addInterceptor(new MyLoggingInterceptor().setLevel(MyLoggingInterceptor.Level.BODY))
                    .build();
        }
    }
}
